package com.bmicpd.gzh.service;

import com.bmicpd.gzh.pojo.RealTimePushMessagePojo;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 主要用于防止相同的文章存入es中
 * @author ytree
 */
public class RepetitionRemoveService {

    private Logger logger = LoggerFactory.getLogger(RepetitionRemoveService.class);

    /**
     * 如果查询结果为0则返回true, 否则返回false
     * @param pushMessagePojo 微信机器人推送的监听消息体
     * @param transportClient es 连接对象
     * @param index es 索引
     * @param type es 类型
     * @return boolean
     */
    public boolean removeRepetition(RealTimePushMessagePojo pushMessagePojo, TransportClient transportClient, String index, String type){

        String appUrl = pushMessagePojo.getApp_url();

        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index)
                .setTypes(type).setTimeout(TimeValue.timeValueMillis(500))
                .setQuery(QueryBuilders.matchPhraseQuery("irUrlName", appUrl));

        long totalHits = searchRequestBuilder.get().getHits().getTotalHits();
        logger.info("RepetitionRemoveService : { totalHits : {}}", totalHits);

        return totalHits == 0;

    }
}
